<template>
  <div class="app-container">
    <el-dialog
      v-model="dealerDialogVisible"
      title="发放对象"
      width="26%"
      :show-close="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <el-form
        ref="formRef"
        :model="dealerForm"
        :rules="dealerRules"
        v-loading="dealerLoading"
      >
        <el-form-item prop="name">
          <el-input
            v-model="dealerForm.name"
            placeholder="请输入单位名称"
            clearable
          ></el-input>
        </el-form-item>
        <p class="form_label">添加底图</p>
        <el-form-item prop="name">
          <div class="flex">
            <upload-img
              v-model:file-list="dealerForm.qrCodeBackgroundImg"
              :files="dealerForm.qrCodeBackgroundImg"
              :limit="1"
              :width="400"
              :height="851"
              @change="changeQrCodeBackgroundImg"
              ref="qrCodeBackgroundImgRef"
            >
              <template #upload-button>
                <div class="upload_btn">
                  <p class="upload_add">
                    <img src="@/assets/images/icon/upload_add.png" />
                  </p>
                  <p class="upload_txt">上传图片</p>
                </div>
              </template>
            </upload-img>
            <div class="form_tips">
              <p>
                <span class="text-color-D43030">*</span
                >支持JPG/PNG格式，建议尺寸400×851像素
              </p>
              <p>
                <span class="text-color-D43030">*</span
                >系统将自动在海报正中央生成二维码（覆盖区域约204×204px），请确保该区域无关键内容
              </p>
            </div>
          </div>
        </el-form-item>
        <p class="form_label mt-6">添加活动图</p>
        <el-form-item prop="name">
          <div></div>
          <div class="flex">
            <upload-img
              v-model:file-list="dealerForm.activityBackgroundImg"
              :files="dealerForm.activityBackgroundImg"
              :limit="1"
              :width="430"
              :height="930"
              @change="changeActivityBackgroundImg"
              ref="activityBackgroundImgRef"
            >
              <template #upload-button>
                <div class="upload_btn">
                  <p class="upload_add">
                    <img src="@/assets/images/icon/upload_add.png" />
                  </p>
                  <p class="upload_txt">上传图片</p>
                </div>
              </template>
            </upload-img>
            <div class="form_tips">
              <p>
                <span class="text-color-D43030">*</span
                >支持JPG/PNG格式，建议尺寸430×930像素
              </p>
              <p>
                <span class="text-color-D43030">*</span
                >下方留出400x277区域，用于填写手机号和验证码，请确保该区域无关键内容
              </p>
              <div class="color_box flex items-center">
                <el-color-picker v-model="dealerForm.color"></el-color-picker>
                <p class="ml-2">
                  <span class="text-color-D43030">*</span>请选择按钮颜色
                </p>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item> </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleQrCode">生成二维码</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="qrCodeDialogVisible"
      title="生成二维码"
      width="30%"
      :show-close="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <div v-loading="qrCodeLoading">
        <el-image :src="qrCodeUrl" fit="contain" style="width: 100%" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleQrCodeClose">关闭</el-button>
          <el-button type="primary" @click="handleQrCodeDow"
            >下载并保存</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { addCouponsDealer, addCouponsQrCode } from "@/api/coupon/coupon"
import uploadImg from "@/components/Upload/uploadImg.vue"
import { ElMessage, FormInstance } from 'element-plus'

// 定义 emits
const emit = defineEmits(['refreshShow'])

// 定义响应式数据
const dealerDialogVisible = ref(false)
const dealerLoading = ref(false)
const qrCodeDialogVisible = ref(false)
const qrCodeLoading = ref(false)
const qrCodeUrl = ref<string | null>(null)
const formRef = ref<FormInstance | null>(null)
const qrCodeBackgroundImgRef = ref<InstanceType<typeof uploadImg> | null>(null)
const activityBackgroundImgRef = ref<InstanceType<typeof uploadImg> | null>(null)

const dealerForm = reactive({
  couponsId: null as number | null,
  name: null as string | null,
  qrCodeBackgroundImg: null as string | null,
  activityBackgroundImg: null as string | null,
  color: null as string | null,
})

const qrCodeForm = reactive({
  dealerId: null as number | null,
  couponsId: null as number | null,
  qrCodeBackgroundImg: null as string | null,
  activityBackgroundImg: null as string | null,
  activityOtherJson: null as string | null,
  color: null as string | null,
})

const dealerRules = {
  name: [{ required: true, message: "请输入单位名称", trigger: "blur" }],
}

// 加载数据
const init = (val: number) => {
  Object.assign(dealerForm, {
    couponsId: null,
    name: null,
    qrCodeBackgroundImg: null,
    activityBackgroundImg: null,
    color: null,
  })
  dealerForm.couponsId = val
  qrCodeForm.couponsId = val
  dealerDialogVisible.value = true
}

// 创建经销商
const handleQrCode = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      if (dealerForm.color == null) {
        ElMessage.error("请选择按钮颜色")
        return
      }
      dealerLoading.value = true
      addCouponsDealer(dealerForm)
        .then((res: any) => {
          if (res.code == 200) {
            qrCodeForm.dealerId = res.data.id
            getGenerateQrCode()
          } else {
            dealerLoading.value = false
            ElMessage.error(res.msg)
          }
        })
        .catch(() => {
          dealerLoading.value = false
        })
    }
  })
}

// 生成二维码
const getGenerateQrCode = () => {
  qrCodeForm.qrCodeBackgroundImg = dealerForm.qrCodeBackgroundImg
  qrCodeForm.activityBackgroundImg = dealerForm.activityBackgroundImg
  qrCodeForm.color = dealerForm.color
  addCouponsQrCode(qrCodeForm)
    .then((res: any) => {
      dealerLoading.value = false
      if (res.code == 200) {
        dealerDialogVisible.value = false
        qrCodeDialogVisible.value = true
        qrCodeUrl.value = res.data.url
      } else {
        ElMessage.error(res.msg)
      }
    })
    .catch(() => {
      dealerLoading.value = false
    })
}

// 关闭
const handleClose = () => {
  dealerDialogVisible.value = false
  emit("refreshShow")
}

// 二维码关闭
const handleQrCodeClose = () => {
  qrCodeDialogVisible.value = false
  emit("refreshShow")
}

// 下载并保存
const handleQrCodeDow = () => {
  if (!qrCodeUrl.value) return
  const imageUrl = qrCodeUrl.value
  const xhr = new XMLHttpRequest()
  xhr.open("GET", imageUrl, true)
  xhr.responseType = "blob"
  const imgSubName = dealerForm.name || "qrcode"
  xhr.onload = () => {
    if (xhr.status === 200) {
      const url = window.URL.createObjectURL(xhr.response)
      const link = document.createElement("a")
      link.href = url
      link.download = imgSubName
      link.click()
    } else {
      ElMessage.error("此照片不支持下载")
    }
  }
  xhr.send()
}

// 处理二维码底图
const changeQrCodeBackgroundImg = (data: any[]) => {
  dealerForm.qrCodeBackgroundImg = data
    .map((item) => item.url)
    .join(",")
  formRef.value?.clearValidate("qrCodeBackgroundImg")
}

// 处理活动底图
const changeActivityBackgroundImg = (data: any[]) => {
  dealerForm.activityBackgroundImg = data
    .map((item) => item.url)
    .join(",")
  formRef.value?.clearValidate("activityBackgroundImg")
}

// 暴露方法给父组件
defineExpose({
  init
})
</script>

<style scoped lang="scss">
:deep(.el-dialog) {
  .el-dialog__header {
    border-radius: 6px 6px 0 0;
    background: rgba(243, 244, 246, 1);
    padding: 12px 15px;
    .el-dialog__title {
      font-size: 14px;
      color: #383838;
    }
  }
  .el-dialog__body {
    padding: 13px 42px 10px 40px;
  }
  .el-form-item {
    margin-bottom: 15px;
  }
  .el-table thead tr th.el-table__cell {
    padding: 10px 0;
  }
  .form_label {
    font-size: 14px;
    color: #0081ff;
    line-height: 21px;
    margin-bottom: 5px;
  }
  .form_tips {
    margin-left: 7px;
    p {
      font-size: 12px;
      line-height: 16px;
      color: #808080;
    }
  }
  .color_box {
    margin-top: 13px;
  }
  .upload_btn {
    width: 95px;
    height: 104px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-sizing: border-box;
    .upload_add {
      margin-top: 22px;
      img {
        width: 25px;
        height: 30px;
      }
    }
    .upload_txt {
      margin-top: 18px;
      font-size: 12px;
      line-height: 18px;
    }
  }
  .dialog-footer {
    .el-button--primary {
      width: 88px;
    }
  }
}
</style>